package com.shopcart.controller;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.shopcart.entity.Product;

/**
 * Listens for the completed orders and finalizes them
 * 
 * @author Gokhan
 * 
 */
@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }, mappedName = "jms/Queue")
public class OrderHandler implements MessageListener {
	@PersistenceContext
	private EntityManager em;

	public OrderHandler() {
	}

	public void onMessage(Message message) {
		if (message instanceof MapMessage) {
			MapMessage mapMessage = (MapMessage) message;
			try {
				long productId = mapMessage
						.getLong("productId");
				int requestedCount = mapMessage
						.getInt("productCount");
				Product product = em.find(Product.class,
						productId);
				if (requestedCount > 0 && product.getQuantity() == 0) {
					product.setQuantity(requestedCount + 10);
					em.persist(product);
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
}